package com.example.sample.activity;

import android.app.AlertDialog;
import android.app.LoaderManager;
import android.content.ContentProviderOperation;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Loader;
import android.content.OperationApplicationException;
import android.content.UriMatcher;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.RemoteException;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.example.app.BaseActivity;
import com.example.sample.R;
import com.example.sample.logic.ChatMessageProvider;

import net.liteheaven.xblib.common.log.XLog;

import java.util.ArrayList;

/**
 * Created by liangy on 2016/11/29.
 */
public class LoaderActivity extends BaseActivity {

    private View insertButton;
    private View deleteButton;
    private View updateButton;
    private View queryButton;
    private ListView riverListView;
    private SimpleCursorAdapter adapter;
    private int id = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_simple_cursor_adapter);
        riverListView = (ListView)findViewById(R.id.riverListView);
        insertButton = findViewById(R.id.insert);
        insertButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentValues contentValues = new ContentValues();
                if (id % 3 == 0){
                    contentValues.put(ChatMessageProvider.CONTENT, "黑龙江");
                }else if (id % 3 == 1){
                    contentValues.put(ChatMessageProvider.CONTENT, "松花江");
                }else if (id % 3 == 2){
                    contentValues.put(ChatMessageProvider.CONTENT, "牡丹江");
                }
                contentValues.put(ChatMessageProvider.NAME, "SB");
                contentValues.put(ChatMessageProvider.ID, (id++));
                getContentResolver().insert(getContentUri(), contentValues);
            }
        });
        deleteButton = findViewById(R.id.delete);
        deleteButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String where = ChatMessageProvider.CONTENT + " = '黑龙江'";
                getContentResolver().delete(getContentUri(), where, null);
            }
        });
        updateButton = findViewById(R.id.update);
        updateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ContentValues contentValues = new ContentValues();
                contentValues.put(ChatMessageProvider.CONTENT, "黑龙江");
                String where = ChatMessageProvider.CONTENT + " != '黑龙江'";
                getContentResolver().update(getContentUri(), contentValues, where, null);
            }
        });
        queryButton = findViewById(R.id.query);
        queryButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getContentResolver().query(getContentUri(), null, null, null, null);
            }
        });
        findViewById(R.id.applyBatch).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
                ContentValues contentValues = new ContentValues();
                for (int i = 0 ; i < 3; i++){
                     if (i % 3 == 0){
                        contentValues.put(ChatMessageProvider.CONTENT, "黑龙江");
                    }else if (i % 3 == 1){
                        contentValues.put(ChatMessageProvider.CONTENT, "松花江");
                    }else if (i % 3 == 2){
                        contentValues.put(ChatMessageProvider.CONTENT, "牡丹江");
                    }
                    contentValues.put(ChatMessageProvider.NAME, "SB");
                    contentValues.put(ChatMessageProvider.ID, (i));


                    ops.add(ContentProviderOperation.newInsert(getContentUri()).withValues(contentValues).build());
                }
                try {
                    getContentResolver().applyBatch(ChatMessageProvider.AUTHORITY, ops);//处理事务
                } catch (RemoteException e) {
                    e.printStackTrace();
                } catch (OperationApplicationException e) {
                    e.printStackTrace();
                }
            }
        });
        initLoader();
        testUrl();
    }

    private void initLoader(){
        getLoaderManager().initLoader(0, null, new LoaderManager.LoaderCallbacks<Cursor>() {

            @Override
            public Loader<Cursor> onCreateLoader(int id, Bundle args) {
                XLog.d(TAG, "onCreateLoader id=" + id + " args=" + args);
                Uri uri = getContentUri();
                CursorLoader cursorLoader = new CursorLoader(LoaderActivity.this,
                        uri, new String[] {
                        ChatMessageProvider.ID,
                        ChatMessageProvider.NAME,
                        ChatMessageProvider.CONTENT },
                        null, null, ChatMessageProvider.ID + " desc limit 0,5");
                return cursorLoader;
            }

            @Override
            public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
                XLog.d(TAG, "onLoadFinished");
                configureAdapter(data);
            }

            @Override
            public void onLoaderReset(Loader<Cursor> loader) {
                XLog.d(TAG, "onLoaderReset");
                adapter.swapCursor(null);
            }
        });
        Uri uri = getContentUri();
        ChatMessageProvider.createTable(uri);
    }

    private void configureAdapter(Cursor cursor){
        if (adapter == null){
            adapter = new SimpleCursorAdapter(this, R.layout.item_simple_cursor_adapter_list, cursor,
                    new String[] { ChatMessageProvider.ID,
                            ChatMessageProvider.NAME,
                            ChatMessageProvider.CONTENT }, new int[] {
                    R.id.id, R.id.name, R.id.len }, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
            riverListView.setAdapter(adapter);
        }else{
            adapter.swapCursor(cursor);
        }
    }

    private void testUrl(){
        Uri uri = Uri.parse("content://com.haha.mycontentproviderdemo.NoteContentProvider/notes");
        Uri uri2 = Uri.withAppendedPath(uri, "#/2");
        String showText = "uri = " + uri.toString() + "\n"
                + "uri2 = " + uri2.toString() + "\n"
                + "getPathSegments = " + uri2.getPathSegments() + "\n"
                + "getAuthority = " + uri2.getAuthority() + "\n"
                + "getEncodedAuthority = " + uri2.getEncodedAuthority() + "\n"
                + "getEncodedPath = " + uri2.getEncodedPath() + "\n"
                + "getEncodedQuery = " + uri2.getEncodedQuery() + "\n"
                + "getEncodedSchemeSpecificPart = " + uri2.getEncodedSchemeSpecificPart() + "\n"
                + "getEncodedUserInfo = " + uri2.getEncodedUserInfo() + "\n"
                + "getEncodedFragment = " + uri2.getEncodedFragment() + "\n"
                + "getPath = " + uri2.getPath().toString() + "\n";

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage(showText);
        AlertDialog alertDialog = builder.create();
        alertDialog.show();

        UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
    }

    private Uri getContentUri(){
        long sessionId = 1500;
        return ChatMessageProvider.getTableUri(sessionId);
    }
}
